from genutils.io import raw_data_columns
from scipy import linspace,arange,linalg,matrix,vectorize,array,hstack,vstack,array
import pylab

#----------------------------------------------------------------------------------
# some synaptic input
#----------------------------------------------------------------------------------
holding_V = [-68,-80,-60,-50.0] # in mV
data_columns = [1,3,5,7]

data = raw_data_columns("09-10-08-vclamp-avg.DAT")
data = array(data)

t_imc   = data.T[0][5010:5700]-500.00
t_sgp   = data.T[0][20010:20700]-2000.00
imc = []
sgp = []
for col in data_columns:
    imc.append(data.T[col][5010:5700])
    sgp.append(data.T[col][20010:20700])


def sfc(c1,c2,E_rev1,E_rev2,hp1,hp2):
    # solve for g1 and g2 given voltage clamp info
    a = matrix([[E_rev1-hp1, E_rev2-hp1],[E_rev1-hp2, E_rev2-hp2]])
    b = matrix([[c1],[c2]])
    x = linalg.solve(a,b)
    return tuple(-1*x)

sfc_vectorized = vectorize(sfc)

def calc_conductances(rev_pot):
    
    for i in range(len(pairs)):
        j,k = pairs[i]
        g1[i],g2[i] = sfc_vectorized(imc[j],imc[k],rev_pot,-79.0,holding_V[j],holding_V[k])
        g1_sgp[i],g2_sgp[i] = sfc_vectorized(sgp[j],sgp[k],rev_pot,\
                                -79.0,holding_V[j],holding_V[k])

def plot_conductances(rev_pot):
    for i in range(len(pairs)):
        j,k = pairs[i]
        # plot imc
        pylab.subplots_adjust(hspace=0.3)
        ax = pylab.subplot(4,2,1)
        pylab.title("IMC stimulation")
        pylab.plot(t_imc,imc[1])
        pylab.ylabel("Held at -80 mV\nCurrent (nA)")
        ax.set_xticks([])
        ax.set_ylim((-0.5,1.0))
        ax.set_yticks([-0.4,0.0,0.4,0.8])
        ax = pylab.subplot(4,2,3)
        pylab.plot(t_imc,imc[2])
        ax.set_ylim((-0.5,1.0))
        ax.set_yticks([-0.4,0.0,0.4,0.8])
        pylab.ylabel("Held at -60 mV\nCurrent (nA)")
        pylab.xlabel("Time after stimulation (ms)")
        # plot sgp
        ax = pylab.subplot(4,2,2)
        pylab.title("SGP stimulation")
        pylab.plot(t_sgp,sgp[1])
        ax.set_ylim((-16,2))
        ax.set_yticks([-15,-10,-5,0])
        ax.set_xticks([])
        ax = pylab.subplot(4,2,4)
        pylab.plot(t_sgp,sgp[2])
        ax.set_ylim((-16,2))
        ax.set_yticks([-15,-10,-5,0])
        # plot conductances
        ax = pylab.subplot(2,1,2)
        pylab.plot(t_sgp,g2_sgp[i],t_sgp,g1_sgp[i], t_imc, g2[i], t_imc, g1[i])
        pylab.ylabel("Conductance (uS)")
        pylab.xlabel("Time after stimulation (ms)")
        ge_imc = r'$g_e$ IMC'
        gi_imc = r'$g_i$ IMC'
        ge_sgp = r'$g_e$ SGP'
        gi_sgp = r'$g_i$ SGP'
        pylab.legend([gi_sgp,ge_sgp,gi_imc,ge_imc])
        pylab.savefig("conductances_for_Dev.png",dpi=150)

    

pairs = []
pairs.append((1,2))

print pairs

g1     = range(len(pairs))
g2     = range(len(pairs))
g1_sgp = range(len(pairs))
g2_sgp = range(len(pairs))
g1_avg = []
g2_avg = []
g1_sgp_avg = []
g2_sgp_avg = []

calc_conductances(0.0)
plot_conductances(0.0)

